package com.dk.common.distribute.rate;

import lombok.RequiredArgsConstructor;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class DistributionRateLimiter implements DistRateLimiter {
    private final RRateLimiter rateLimiter;

    public static DistRateLimiter of(RRateLimiter rateLimiter) {
        return new DistributionRateLimiter(rateLimiter);
    }

    @Override
    public void trySetRate(long rateInInterval, long rateIntervalSecond) {
        rateLimiter.setRate(RateType.OVERALL, rateInInterval,
                rateIntervalSecond, RateIntervalUnit.SECONDS);
    }

    @Override
    public boolean tryAcquire() {
        return rateLimiter.tryAcquire();
    }

    @Override
    public boolean tryAcquire(int permits) {
        return rateLimiter.tryAcquire(permits);
    }

    @Override
    public void acquire() {
        rateLimiter.acquire();
    }

    @Override
    public void acquire(int permits) {
        rateLimiter.acquire(permits);
    }

    @Override
    public boolean tryAcquire(long timeout, TimeUnit unit) {
        return rateLimiter.tryAcquire(timeout, unit);
    }

    @Override
    public boolean tryAcquire(int permits, long timeout, TimeUnit unit) {
        return rateLimiter.tryAcquire(permits, timeout, unit);
    }
}
